package HGbet;

import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;

import java.awt.BorderLayout;

import javax.swing.JLabel;


















import DXQclient.DXQclientManager;
import P8.StoneAgeClient;

import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;

import javax.swing.JScrollPane;

import java.awt.GridLayout;

import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JTable;
import javax.swing.JButton;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;

import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.NumberFormat;
import java.util.Vector;

public class BetSettings {

	private JFrame frame;
	private JTable betRestable;
	private JTextField betAmounttextField;
	private JTextField startBetTimetextField;
	private JTextField endBetTimetextField;
	private JTextField minBetRatiotextField;
	private JTextField maxBetRatiotextField;
	
	
	
	
	
	
	JScrollPane scrollPane = new JScrollPane();

	
	JPanel dxqPankouPanel = new JPanel();

	
	JScrollPane scrollPane_2 = new JScrollPane();

	JPanel rqPankouPanel = new JPanel();

	
	
	
	
	DXQclientManager dxqClientManager= null;
	
	
	public Vector<String[]> showitemVec = new Vector<String[]>();
	
	public Vector<String> dxqpankous = new Vector<String>();
	
	public String rqpankoustr ="";
	
	MyTableModel tableMode = new MyTableModel();
	
	NumberFormat nf = NumberFormat.getInstance();


	/**
	 * Create the application.
	 */
	public BetSettings(DXQclientManager manager) {
		
		dxqClientManager = manager;
		
		initialize();
		frame.setTitle("参数设置");
		frame.setVisible(false);
	}
	
	public void show(){
		frame.setVisible(true);
	}
	
	
	public Vector<String> getbetdxqpans(){
		return dxqpankous;
	}
	
	public String getbetrqpans(){
		return rqpankoustr;
	}
	
	public int getstartbettime(){
		return Integer.parseInt(startBetTimetextField.getText());
	}
	
	public int getendbettime(){
		return Integer.parseInt(endBetTimetextField.getText());
	}
	
	public double getminbetratio(){
		return Double.parseDouble(minBetRatiotextField.getText());
	}
	
	public double getmaxbetratio(){
		return Double.parseDouble(maxBetRatiotextField.getText());
	}
	
	public int getbetamount(){
		return Integer.parseInt(betAmounttextField.getText());
	}
	
	
    public class MyTableModel extends AbstractTableModel  
    {  
        /* 
         * 这里和刚才一样，定义列名和每个数据的值 
         */  
        String[] columnNames =  
        	 { "序号", "联赛", "时间","球队", "投注比分", "单式盘口", "投注盘口" ,"投注水位", "投注结果","投注时间","投注金额"};
        

        /** 
         * 得到数据所对应对象 
         */  
        @Override  
        public Object getValueAt(int rowIndex, int columnIndex)  
        { 
        	
        	try{
        		
        		if(columnIndex == 0){
        			return Integer.toString(rowIndex+1);
        		}else{
        			return showitemVec.elementAt(rowIndex)[columnIndex-1];
        		}
        	}catch(Exception e){
        		e.printStackTrace();
        		return null;
        	}
        	

        	
        	
        }  
        

        
  
        /** 
         * 构造方法，初始化二维数组data对应的数据 
         */  
        public MyTableModel()  
        {  

        }  
  
        // 以下为继承自AbstractTableModle的方法，可以自定义  
        /** 
         * 得到列名 
         */  
        @Override  
        public String getColumnName(int column)  
        {  
            return columnNames[column];  
        }  
          
        /** 
         * 重写方法，得到表格列数 
         */  
        @Override  
        public int getColumnCount()  
        {  
            return columnNames.length;  
        }  
  
        /** 
         * 得到表格行数 
         */  
        @Override  
        public int getRowCount()  
        {         
	        if(null == showitemVec){
	    		return 0;
	    	}
	        
	        //System.out.println(gameDetailsVec.size());
	        
            return showitemVec.size();  
        }  
  

  
        /** 
         * 得到指定列的数据类型 
         */  
        @Override  
        public Class<?> getColumnClass(int columnIndex)  
        {  
            return String.class;
        }  
  
        /** 
         * 指定设置数据单元是否可编辑.这里设置"姓名","学号"不可编辑 
         */  
        @Override  
        public boolean isCellEditable(int rowIndex, int columnIndex)  
        {  
            return false;
        }  
          
        /** 
         * 如果数据单元为可编辑，则将编辑后的值替换原来的值 
         */  
        @Override  
        public void setValueAt(Object aValue, int rowIndex, int columnIndex)  
        {  
            /*detailsData.elementAt(rowIndex)[columnIndex] = (String)aValue;  
            通知监听器数据单元数据已经改变  
            fireTableCellUpdated(rowIndex, columnIndex);  */
        }  
        
        public void updateTable(){
        	fireTableDataChanged();
        }
        
  
    }  
	
	
	
	
	

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 1280, 720);
		frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		frame.getContentPane().setLayout(null);
		
		//JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 40, 400, 200);
		frame.getContentPane().add(scrollPane);
		
		//JPanel dxqPankouPanel = new JPanel();
		scrollPane.setViewportView(dxqPankouPanel);
		dxqPankouPanel.setLayout(new GridLayout(10, 4, 0, 0));
		
		//JScrollPane scrollPane_2 = new JScrollPane();
		scrollPane_2.setBounds(420, 40, 286, 200);
		frame.getContentPane().add(scrollPane_2);
		
		//JPanel rqPankouPanel = new JPanel();
		scrollPane_2.setViewportView(rqPankouPanel);
		rqPankouPanel.setLayout(new GridLayout(10, 4, 0, 0));
		
		
		double rqpankou = 0.0f;
		
		
		for(int i = 0; i < 40; i++){
			
			String pankoustr = "";
			
			if(rqpankou == 0.0){
				pankoustr = "0";
			}else{
				if((int)(rqpankou / 0.25) % 2 == 1){
					
					String left = nf.format(rqpankou - 0.25);
					String right = nf.format(rqpankou + 0.25);
					
					pankoustr = left + "/" + right;
					
				}else{
					pankoustr = nf.format(rqpankou);
				}
			}
			
			
			final JCheckBox checkbox = new JCheckBox(pankoustr);
			rqPankouPanel.add(checkbox);
			
			checkbox.addItemListener(new ItemListener() {
				public void itemStateChanged(ItemEvent e) {
					
					if(e.getStateChange() == ItemEvent.DESELECTED){
						
						//rqpankoustr = "";
						
						
						
					}else{
						
						rqpankoustr = checkbox.getText();
						
						System.out.println(rqpankoustr);
						
						System.out.println("rq SELECTED" + checkbox.getText());
						
						
						
						final Component[] components = rqPankouPanel.getComponents();
						
						for (Component component : components) {
				            if (component instanceof JCheckBox) {
				            	
				            	if(!((JCheckBox) component).getText().equals(rqpankoustr)){
				            		((JCheckBox) component).setSelected(false);
				            	}
				            	
				                
				            }
				        }
						
						
					}
					
				}
			});
			
			rqpankou += 0.25;
			
		}
		
		
		
		
		
		double dxqpankou = 0.0f;
		
		
		
		for(int i = 0; i < 40; i++){
			
			String pankoustr = "";
			
			if(dxqpankou == 0.0){
				pankoustr = "0";
			}else{
				if((int)(dxqpankou / 0.25) % 2 == 1){
					
					String left = nf.format(dxqpankou - 0.25);
					String right = nf.format(dxqpankou + 0.25);
					
					pankoustr = left + "/" + right;
					
				}else{
					pankoustr = nf.format(dxqpankou);
				}
			}
			
			
			final JCheckBox checkbox = new JCheckBox(pankoustr);
			dxqPankouPanel.add(checkbox);
			
			checkbox.addItemListener(new ItemListener() {
				public void itemStateChanged(ItemEvent e) {
					
					if(e.getStateChange() == ItemEvent.DESELECTED){
						
						System.out.println("DESELECTED" + checkbox.getText());
						dxqpankous.remove(checkbox.getText());
						
					}else{
						
						if(!dxqpankous.contains(checkbox.getText() )){
							dxqpankous.add(checkbox.getText());
						}
						
						System.out.println("SELECTED" + checkbox.getText());
						
					}
					
				}
			});
			
			dxqpankou += 0.25;
			
		}
		
		

		
		JLabel label = new JLabel("参与盘口：");
		label.setBounds(10, 0, 82, 40);
		frame.getContentPane().add(label);
		
		JLabel label_1 = new JLabel("让球盘：");
		label_1.setBounds(444, -5, 200, 50);
		frame.getContentPane().add(label_1);
		
		JPanel paramsSettingPanel = new JPanel();
		paramsSettingPanel.setBounds(718, 44, 253, 108);
		frame.getContentPane().add(paramsSettingPanel);
		paramsSettingPanel.setLayout(new GridLayout(4, 1));
		
		JPanel panelSub1 = new JPanel(new GridLayout(1,4));
		
		
		paramsSettingPanel.add(panelSub1);
		
		JLabel label_3 = new JLabel("投注金额");
		panelSub1.add(label_3);
		
		betAmounttextField = new JTextField();
		betAmounttextField.setText("100");
		panelSub1.add(betAmounttextField);
		betAmounttextField.setColumns(10);
		
		JLabel label_4 = new JLabel("");
		panelSub1.add(label_4);
		
		JLabel label_5 = new JLabel("");
		panelSub1.add(label_5);
		
		
		JPanel panelSub2 = new JPanel(new GridLayout(1,4));
		
		paramsSettingPanel.add(panelSub2);
		
		JLabel label_6 = new JLabel("时间");
		panelSub2.add(label_6);
		
		startBetTimetextField = new JTextField();
		startBetTimetextField.setText("0");
		startBetTimetextField.setColumns(10);
		panelSub2.add(startBetTimetextField);
		
		JLabel label_7 = new JLabel("        至");
		panelSub2.add(label_7);
		
		endBetTimetextField = new JTextField();
		endBetTimetextField.setText("90");
		endBetTimetextField.setColumns(10);
		panelSub2.add(endBetTimetextField);
		
		
		JPanel panelSub3 = new JPanel(new GridLayout(1,4));
		paramsSettingPanel.add(panelSub3);
		
		JLabel label_8 = new JLabel("水位");
		panelSub3.add(label_8);
		
		minBetRatiotextField = new JTextField();
		minBetRatiotextField.setText("0.1");
		minBetRatiotextField.setColumns(10);
		panelSub3.add(minBetRatiotextField);
		
		JLabel label_9 = new JLabel("        至");
		panelSub3.add(label_9);
		
		maxBetRatiotextField = new JTextField();
		maxBetRatiotextField.setText("1.0");
		maxBetRatiotextField.setColumns(10);
		panelSub3.add(maxBetRatiotextField);
		
		
		
		
		
		JLabel label_2 = new JLabel("参数设置：");
		label_2.setBounds(718, 0, 200, 40);
		frame.getContentPane().add(label_2);
		
		JScrollPane scrollPane_1 = new JScrollPane();
		scrollPane_1.setBounds(10, 253, 1244, 429);
		frame.getContentPane().add(scrollPane_1);
		
		betRestable = new JTable(tableMode);
		scrollPane_1.setViewportView(betRestable);
		
		JButton btnSaveParamsButton = new JButton("保存设置");
		btnSaveParamsButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				
				
				
					
					try{		
						
						if(savebetparamstofile()){
							JOptionPane.showMessageDialog(null,"保存投注设置成功");
						}else{
							JOptionPane.showMessageDialog(null,"保存投注设置失败");
						}
						

					}catch(Exception ex){
						ex.printStackTrace();
					}
					
					


				
				
				
				
			}
		});
		btnSaveParamsButton.setBounds(979, 197, 93, 23);
		frame.getContentPane().add(btnSaveParamsButton);
		

	}
	
	
	
	public void recoverbetparamsfromfile(){
		try{
			
			File file = new File("data/" + dxqClientManager.getAccount() + "/betparams.txt");
			
			if(!file.exists()){
				return;
			}

			BufferedReader freader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
			
			
			
			
			
			String str = "";
			
			int linenum = 0;

			while ((str = freader.readLine()) != null) {
				
				if(linenum == 0){
					String[] contents = str.split(",");
					if(contents.length == 2){
						startBetTimetextField.setText(contents[0]);
						endBetTimetextField.setText(contents[1]);
					}
				}else if(linenum == 1){
					String[] contents = str.split(",");
					for(String content : contents){
						dxqpankous.add(content);
					}
					
					final Component[] components = dxqPankouPanel.getComponents();
					
					for (Component component : components) {
			            if (component instanceof JCheckBox) {
			            	
			            	if(dxqpankous.contains(((JCheckBox) component).getText())){
			            		((JCheckBox) component).setSelected(true);
			            	}
			            	
			                
			            }
			        }
					
					
				}else if(linenum == 2){
					rqpankoustr = str;
					
					
					final Component[] components = rqPankouPanel.getComponents();
					
					for (Component component : components) {
			            if (component instanceof JCheckBox) {
			            	
			            	if(((JCheckBox) component).getText().equals(rqpankoustr)){
			            		((JCheckBox) component).setSelected(true);
			            	}
			            	
			                
			            }
			        }
					
					
				}else if(linenum == 3){
					String[] contents = str.split(",");
					if(contents.length == 2){
						minBetRatiotextField.setText(contents[0]);
						maxBetRatiotextField.setText(contents[1]);
					}
				}
				else if(linenum == 4){
					betAmounttextField.setText(str);
				}else if(linenum == 5){
					
				}
				
				linenum++;

			}
			
			setAccountsListMessage();
			
			
			if(null != freader){
				freader.close();
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
	
	
	
	
	public boolean savebetparamstofile(){
		try{
			
			File filefolder = new File("data/" + dxqClientManager.getAccount() + "/");
			
			if(!filefolder.exists()){
				filefolder.mkdir();
			}
			
			File file = new File("data/" + dxqClientManager.getAccount() + "/betparams.txt");

			if(!file.exists()){	
				file.createNewFile();
			}
			
			BufferedWriter fwlocal = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), "UTF-8"));

			
			
			
			
			String str = startBetTimetextField.getText() + "," + endBetTimetextField.getText();
			fwlocal.append(str);
			fwlocal.newLine();
			fwlocal.flush();		
			
			str = "";
			
			int index = 0;
			for(String dxp : dxqpankous){
				if(index == 0){
					str = dxp;
				}else{
					str = str + "," + dxp;
				}
				index++;
			}
			fwlocal.append(str);
			fwlocal.newLine();
			fwlocal.flush();
			
			
			str = rqpankoustr;
			
			fwlocal.append(str);
			fwlocal.newLine();
			fwlocal.flush();
			
			
			str = minBetRatiotextField.getText() + "," + maxBetRatiotextField.getText();
			
			fwlocal.append(str);
			fwlocal.newLine();
			fwlocal.flush();
			
			
			
			str = betAmounttextField.getText();
			fwlocal.append(str);
			fwlocal.newLine();
			fwlocal.flush();
			
			
			fwlocal.close();
			setAccountsListMessage();
			return true;
			
			
			
		}catch(Exception e){
			e.printStackTrace();
			
		}
		
		return false;
	}
	
	
	
	public void setAccountsListMessage() {
		
		StoneAgeClient.betAccountsListWindow.setBetTime(dxqClientManager, startBetTimetextField.getText() + "," + endBetTimetextField.getText());
		//StoneAgeClient.betAccountsListWindow.setXiabanShuiwei(dxqClientManager, maxinplayratiotxt.getText() + "," + mininplayratiotxt.getText());
		
		String str = "";
		
		int index = 0;
		for(String dxp : dxqpankous){
			if(index == 0){
				str = dxp;
			}else{
				str = str + "," + dxp;
			}
			
			index++;
			
		}
		
		StoneAgeClient.betAccountsListWindow.setBetDxqpankou(dxqClientManager, str);
		
		str = rqpankoustr;
		
		
		StoneAgeClient.betAccountsListWindow.setBetRqpankou(dxqClientManager, str);
		
		StoneAgeClient.betAccountsListWindow.setBetRatio(dxqClientManager, minBetRatiotextField.getText() + "," + maxBetRatiotextField.getText());
		StoneAgeClient.betAccountsListWindow.setBetAmount(dxqClientManager, betAmounttextField.getText());
		StoneAgeClient.betAccountsListWindow.setBetTimes(dxqClientManager, "1");
		
	}
	
	public void updateBetlistVec(Vector<String[]> list){
		
		if(showitemVec.size() != 0){
			showitemVec.clear();
		}
		
		
		for(int i = 0; i < list.size(); i++){
			
			String[] item = {list.elementAt(i)[BETRESINDEX.LEAGUE.ordinal()], list.elementAt(i)[BETRESINDEX.TIME.ordinal()], list.elementAt(i)[BETRESINDEX.TEAM.ordinal()],
					list.elementAt(i)[BETRESINDEX.SCORE.ordinal()],list.elementAt(i)[BETRESINDEX.DANSHIRQPK.ordinal()],list.elementAt(i)[BETRESINDEX.CURRENTPK.ordinal()],
							list.elementAt(i)[BETRESINDEX.BETRATIO.ordinal()],list.elementAt(i)[BETRESINDEX.BETRES.ordinal()],list.elementAt(i)[BETRESINDEX.BETTIME.ordinal()],
							list.elementAt(i)[BETRESINDEX.BETGOLD.ordinal()]};
			
			showitemVec.add(item);
			
		}
		
		updateShowItem();
		
	}
	
	public void updateShowItem(){
		

		
		
		
		tableMode.updateTable();
		
		setOneRowBackgroundColor();
		

	}
	
    public void setOneRowBackgroundColor() {
    	

    	
        try {  
            DefaultTableCellRenderer tcr = new DefaultTableCellRenderer() {
            	
            	
  
                public Component getTableCellRendererComponent(JTable table,  
                        Object value, boolean isSelected, boolean hasFocus,  
                        int row, int column) {  

                	
                    if (row%2==1) {  
                    	setBackground(new Color(246,246,246));  
                        
                    }else{  
                        setBackground(new Color(222,222,243));  
                    	//setBackground(new Color(1,1,1));  
                      
                    }  
                    
                    setHorizontalAlignment(JLabel.CENTER);
  
                    return super.getTableCellRendererComponent(table, value,  
                            isSelected, hasFocus, row, column);  
                }  
            };  
            int columnCount = betRestable.getColumnCount();  
            for (int i = 0; i < columnCount; i++) {  
            	betRestable.getColumn(betRestable.getColumnName(i)).setCellRenderer(tcr);
            }  
        } catch (Exception ex) {  
            ex.printStackTrace();  
        }  
    }  
	
	
	
	
}
